package com.cms.utils;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.cms.service.IUserService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

@Component
public class TokenUtils {

    private static IUserService staticUserService;

    @Resource
    private IUserService iUserService;

    @PostConstruct
    public void setiUserService(){
        staticUserService = iUserService;
    }


    /**
     * 生成token
     */
    public static String genToken(String userId, String sign) {//注意，这里的userId貌似是用户名跟密码，留意一下自己的是否一致
        return JWT.create().withAudience(userId)//将user id 保存到token 里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),24))//2小时后token过期
                .sign(Algorithm.HMAC256(sign));//以password 作为 token 的密钥
    }

    /**
     * 获取当前登录的用户的信息
     * @return user对象
     */
//    public static User getCurrentUser(){
//        try {
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            String token = request.getHeader("token");
//            if (StrUtil.isNotBlank(token)){
//                String userId = JWT.decode(token).getAudience().get(0);
//                return staticUserService.getById(Integer.valueOf(userId));
//            }
//        }catch (Exception e){
//            return null;
//        }
//        return null;
//    }
}
